package com.frinder.base.utils;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * @author frinder
 * @date 2018/8/13
 * @Description: spring spel 获取属性(key)值辅助类
 */
public class SpelUtils {

    public static final SpelUtils SPEL_UTILS = new SpelUtils();

    private SpelUtils() {
    }

    private final Logger logger = LoggerFactory.getLogger(SpelUtils.class);

    /**
     * 获取 key
     *
     * @param beanFactory
     * @param key
     * @param joinPoint
     * @return
     */
    public String generateKey(BeanFactory beanFactory, String key, JoinPoint joinPoint) {
        try {
            StandardEvaluationContext context = getContextVariables(joinPoint);
            context.setBeanResolver(new BeanFactoryResolver(beanFactory));
            ExpressionParser parser = new SpelExpressionParser();
            Expression exp = parser.parseExpression(key);
            String value = exp.getValue(context, String.class);
            return value;
        } catch (Exception e) {
            logger.debug("*** 解析 SPEL 失败");
            return "";
        }
    }

    /**
     * @param joinPoint
     * @return
     */
    private StandardEvaluationContext getContextVariables(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        StandardEvaluationContext context = new StandardEvaluationContext(args);
        if (args == null || args.length <= 0) {
            return context;
        }
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = methodSignature.getParameterNames();
        for (int i = 0; i < args.length; i++) {
            context.setVariable(parameterNames[i], args[i]);
        }
        return context;
    }
}
